<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>MySQL索引如何优化？ | Sobremesa的个人空间</title><meta name="keywords" content="MySql"><meta name="author" content="Li YunBO"><meta name="copyright" content="Li YunBO"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><meta name="description" content="MySQL索引如何优化？索引优化规则 1、like语句的前导模糊查询不能使用索引1select * from doc where title like &#39;%XX&#39;；   --不能使用索引 select * from doc where title like &#39;XX%&#39;；   --非前导模糊查询，可以使用索引   因为页面搜索严禁左模糊或者全模糊，如果需要可以使用搜索">
<meta property="og:type" content="article">
<meta property="og:title" content="MySQL索引如何优化？">
<meta property="og:url" content="http://example.com/2021/04/27/MySql%E7%B4%A2%E5%BC%95%E4%BC%98%E5%8C%96/index.html">
<meta property="og:site_name" content="Sobremesa的个人空间">
<meta property="og:description" content="MySQL索引如何优化？索引优化规则 1、like语句的前导模糊查询不能使用索引1select * from doc where title like &#39;%XX&#39;；   --不能使用索引 select * from doc where title like &#39;XX%&#39;；   --非前导模糊查询，可以使用索引   因为页面搜索严禁左模糊或者全模糊，如果需要可以使用搜索">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="http://example.com/img/%E5%A4%B4%E5%83%8F2.jpg">
<meta property="article:published_time" content="2021-04-26T16:00:00.000Z">
<meta property="article:modified_time" content="2021-08-09T12:50:52.999Z">
<meta property="article:author" content="Li YunBO">
<meta property="article:tag" content="MySql">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/img/%E5%A4%B4%E5%83%8F2.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/2021/04/27/MySql%E7%B4%A2%E5%BC%95%E4%BC%98%E5%8C%96/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  ClickShowText: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
};

var saveToLocal = {
  set: function setWithExpiry(key, value, ttl) {
    const now = new Date()
    const expiryDay = ttl * 86400000
    const item = {
      value: value,
      expiry: now.getTime() + expiryDay,
    }
    localStorage.setItem(key, JSON.stringify(item))
  },

  get: function getWithExpiry(key) {
    const itemStr = localStorage.getItem(key)

    if (!itemStr) {
      return undefined
    }
    const item = JSON.parse(itemStr)
    const now = new Date()

    if (now.getTime() > item.expiry) {
      localStorage.removeItem(key)
      return undefined
    }
    return item.value
  }
}

// https://stackoverflow.com/questions/16839698/jquery-getscript-alternative-in-native-javascript
const getScript = url => new Promise((resolve, reject) => {
  const script = document.createElement('script')
  script.src = url
  script.async = true
  script.onerror = reject
  script.onload = script.onreadystatechange = function() {
    const loadState = this.readyState
    if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
    script.onload = script.onreadystatechange = null
    resolve()
  }
  document.head.appendChild(script)
})</script><script id="config_change">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-08-09 20:50:52'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(function () {  window.activateDarkMode = function () {
    document.documentElement.setAttribute('data-theme', 'dark')
    if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
    }
  }
  window.activateLightMode = function () {
    document.documentElement.setAttribute('data-theme', 'light')
   if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
    }
  }
  const autoChangeMode = 'false'
  const t = saveToLocal.get('theme')
  if (autoChangeMode === '1') {
    const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
    const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
    const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
    const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified
    if (t === undefined) {
      if (isLightMode) activateLightMode()
      else if (isDarkMode) activateDarkMode()
      else if (isNotSpecified || hasNoSupport) {
        const now = new Date()
        const hour = now.getHours()
        const isNight = hour <= 6 || hour >= 18
        isNight ? activateDarkMode() : activateLightMode()
      }
      window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
        if (saveToLocal.get('theme') === undefined) {
          e.matches ? activateDarkMode() : activateLightMode()
        }
      })
    } else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else if (autoChangeMode === '2') {
    const now = new Date()
    const hour = now.getHours()
    const isNight = hour <= 6 || hour >= 18
    if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
    else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else {
    if (t === 'dark') activateDarkMode()
    else if (t === 'light') activateLightMode()
  }const asideStatus = saveToLocal.get('aside-status')
if (asideStatus !== undefined) {
   if (asideStatus === 'hide') {
     document.documentElement.classList.add('hide-aside')
   } else {
     document.documentElement.classList.remove('hide-aside')
   }
}})()</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Sobremesa的个人空间" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="/img/%E5%A4%B4%E5%83%8F2.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">193</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">25</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">Categories</div><div class="length-num">18</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 档案</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/music/"><i class="fa-fw fas fa-music"></i><span> Music</span></a></li><li><a class="site-page" href="/movies/"><i class="fa-fw fas fa-video"></i><span> Movie</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Sobremesa的个人空间</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 档案</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/music/"><i class="fa-fw fas fa-music"></i><span> Music</span></a></li><li><a class="site-page" href="/movies/"><i class="fa-fw fas fa-video"></i><span> Movie</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">MySQL索引如何优化？</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2021-04-26T16:00:00.000Z" title="Created 2021-04-27 00:00:00">2021-04-27</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2021-08-09T12:50:52.999Z" title="Updated 2021-08-09 20:50:52">2021-08-09</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/MySql/">MySql</a></span></div><div class="meta-secondline"> <span class="post-meta-separator">|</span><span class="post-meta-pv-cv"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="MySQL索引如何优化？"><a href="#MySQL索引如何优化？" class="headerlink" title="MySQL索引如何优化？"></a>MySQL索引如何优化？</h1><p><strong>索引优化规则</strong></p>
<h2 id="1、like语句的前导模糊查询不能使用索引"><a href="#1、like语句的前导模糊查询不能使用索引" class="headerlink" title="1、like语句的前导模糊查询不能使用索引"></a>1、like语句的前导模糊查询不能使用索引</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">select * from doc where title like &#39;%XX&#39;；   --不能使用索引 select * from doc where title like &#39;XX%&#39;；   --非前导模糊查询，可以使用索引 <br></code></pre></td></tr></table></figure>

<p>因为页面搜索严禁左模糊或者全模糊，如果需要可以使用搜索引擎来解决。</p>
<h2 id="2、union、in、or-都能够命中索引，建议使用-in"><a href="#2、union、in、or-都能够命中索引，建议使用-in" class="headerlink" title="2、union、in、or 都能够命中索引，建议使用 in"></a><strong>2、union、in、or 都能够命中索引，建议使用 in</strong></h2><p>union能够命中索引，并且MySQL 耗费的 CPU 最少。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">select * from doc where status&#x3D;1 union all select * from doc where status&#x3D;2; <br></code></pre></td></tr></table></figure>

<p>in能够命中索引，查询优化耗费的 CPU 比 union all 多，但可以忽略不计，一般情况下建议使用 in。</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs csharp"><span class="hljs-keyword">select</span> * <span class="hljs-function"><span class="hljs-keyword">from</span> doc <span class="hljs-keyword">where</span> status <span class="hljs-title">in</span> (<span class="hljs-params"><span class="hljs-number">1</span>, <span class="hljs-number">2</span></span>)</span>; <br></code></pre></td></tr></table></figure>

<p>or 新版的 MySQL 能够命中索引，查询优化耗费的 CPU 比 in多，不建议频繁用or。</p>
<figure class="highlight fortran"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs fortran"><span class="hljs-keyword">select</span> * from doc <span class="hljs-keyword">where</span> <span class="hljs-keyword">status</span> = <span class="hljs-number">1</span> or <span class="hljs-keyword">status</span> = <span class="hljs-number">2</span> <br></code></pre></td></tr></table></figure>

<p>补充：有些地方说在where条件中使用or，索引会失效，造成全表扫描，这是个误区：</p>
<ul>
<li>①要求where子句使用的所有字段，都必须建立索引;</li>
<li>②如果数据量太少，mysql制定执行计划时发现全表扫描比索引查找更快，所以会不使用索引;</li>
<li>③确保mysql版本5.0以上，且查询优化器开启了index_merge_union=on, 也就是变量optimizer_switch里存在index_merge_union且为on。</li>
</ul>
<h2 id="3、负向条件查询不能使用索引"><a href="#3、负向条件查询不能使用索引" class="headerlink" title="3、负向条件查询不能使用索引"></a><strong>3、负向条件查询不能使用索引</strong></h2><ul>
<li>负向条件有：!=、&lt;&gt;、not in、not exists、not like 等。</li>
<li>例如下面SQL语句：</li>
</ul>
<figure class="highlight axapta"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs axapta"><span class="hljs-keyword">select</span> * <span class="hljs-keyword">from</span> doc <span class="hljs-keyword">where</span> status != <span class="hljs-number">1</span> and status != <span class="hljs-number">2</span>; <br></code></pre></td></tr></table></figure>

<p>可以优化为 in 查询：</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs csharp"><span class="hljs-keyword">select</span> * <span class="hljs-function"><span class="hljs-keyword">from</span> doc <span class="hljs-keyword">where</span> status <span class="hljs-title">in</span> (<span class="hljs-params"><span class="hljs-number">0</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span></span>)</span>; <br></code></pre></td></tr></table></figure>

<h2 id="4、联合索引最左前缀原则"><a href="#4、联合索引最左前缀原则" class="headerlink" title="4、联合索引最左前缀原则"></a><strong>4、联合索引最左前缀原则</strong></h2><ul>
<li>如果在(a,b,c)三个字段上建立联合索引，那么他会自动建立 a| (a,b) | (a,b,c)组索引。</li>
<li>登录业务需求，SQL语句如下：</li>
</ul>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs routeros">select uid, login_time <span class="hljs-keyword">from</span><span class="hljs-built_in"> user </span>where <span class="hljs-attribute">login_name</span>=? <span class="hljs-attribute">andpasswd</span>=? <br></code></pre></td></tr></table></figure>

<ul>
<li>可以建立(login_name, passwd)的联合索引。因为业务上几乎没有passwd 的单条件查询需求，而有很多login_name 的单条件查询需求，所以可以建立(login_name, passwd)的联合索引，而不是(passwd, login_name)。</li>
</ul>
<ol>
<li>建立联合索引的时候，区分度最高的字段在最左边</li>
<li>存在非等号和等号混合判断条件时，在建立索引时，把等号条件的列前置。如 where a&gt;? and b=?，那么即使a 的区分度更高，也必须把 b 放在索引的最前列。</li>
<li>最左前缀查询时，并不是指SQL语句的where顺序要和联合索引一致。</li>
</ol>
<ul>
<li>下面的 SQL 语句也可以命中 (login_name, passwd) 这个联合索引：</li>
</ul>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs routeros">select uid, login_time <span class="hljs-keyword">from</span><span class="hljs-built_in"> user </span>where <span class="hljs-attribute">passwd</span>=? <span class="hljs-attribute">andlogin_name</span>=? <br></code></pre></td></tr></table></figure>

<ul>
<li>但还是建议 where 后的顺序和联合索引一致，养成好习惯。</li>
</ul>
<p>假如index(a,b,c), where a=3 and b like ‘abc%’ and c=4，a能用，b能用，c不能用。</p>
<h2 id="5、不能使用索引中范围条件右边的列-范围列可以用到索引-，范围列之后列的索引全失效"><a href="#5、不能使用索引中范围条件右边的列-范围列可以用到索引-，范围列之后列的索引全失效" class="headerlink" title="5、不能使用索引中范围条件右边的列(范围列可以用到索引)，范围列之后列的索引全失效"></a><strong>5、不能使用索引中范围条件右边的列(范围列可以用到索引)，范围列之后列的索引全失效</strong></h2><ul>
<li>范围条件有：&lt;、&lt;=、&gt;、&gt;=、between等。</li>
<li>索引最多用于一个范围列，如果查询条件中有两个范围列则无法全用到索引。</li>
<li>假如有联合索引 (empno、title、fromdate)，那么下面的 SQL 中 emp_no 可以用到索引，而title 和 from_date 则使用不到索引。</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs python">select * <span class="hljs-keyword">from</span> employees.titles where emp_no &lt; <span class="hljs-number">10010</span><span class="hljs-string">&#x27; and title=&#x27;</span>Senior Enginee<span class="hljs-string">r&#x27;and from_date between &#x27;</span><span class="hljs-number">1986</span>-01-01<span class="hljs-string">&#x27; and &#x27;</span><span class="hljs-number">1986</span>-<span class="hljs-number">12</span>-<span class="hljs-number">31</span><span class="hljs-string">&#x27; </span><br></code></pre></td></tr></table></figure>

<h2 id="6、不要在索引列上面做任何操作-计算、函数-，否则会导致索引失效而转向全表扫描"><a href="#6、不要在索引列上面做任何操作-计算、函数-，否则会导致索引失效而转向全表扫描" class="headerlink" title="6、不要在索引列上面做任何操作(计算、函数)，否则会导致索引失效而转向全表扫描"></a><strong>6、不要在索引列上面做任何操作(计算、函数)，否则会导致索引失效而转向全表扫描</strong></h2><p>例如下面的 SQL 语句，即使 date 上建立了索引，也会全表扫描：</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs csharp"><span class="hljs-keyword">select</span> * <span class="hljs-function"><span class="hljs-keyword">from</span> doc <span class="hljs-keyword">where</span> <span class="hljs-title">YEAR</span>(<span class="hljs-params">create_time</span>) &lt;</span>= <span class="hljs-string">&#x27;2016&#x27;</span>; <br></code></pre></td></tr></table></figure>

<p>可优化为值计算，如下：</p>
<figure class="highlight axapta"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs axapta"><span class="hljs-keyword">select</span> * <span class="hljs-keyword">from</span> doc <span class="hljs-keyword">where</span> create_time &lt;= <span class="hljs-string">&#x27;2016-01-01&#x27;</span>; <br></code></pre></td></tr></table></figure>

<p>比如下面的 SQL 语句：</p>
<figure class="highlight axapta"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs axapta"><span class="hljs-keyword">select</span> * <span class="hljs-keyword">from</span> <span class="hljs-keyword">order</span> <span class="hljs-keyword">where</span> <span class="hljs-built_in">date</span> &lt; = CURDATE()； <br></code></pre></td></tr></table></figure>

<p>可以优化为：</p>
<figure class="highlight axapta"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs axapta"><span class="hljs-keyword">select</span> * <span class="hljs-keyword">from</span> <span class="hljs-keyword">order</span> <span class="hljs-keyword">where</span> <span class="hljs-built_in">date</span> &lt; = <span class="hljs-string">&#x27;2018-01-2412:00:00&#x27;</span>; <br></code></pre></td></tr></table></figure>

<h2 id="7、强制类型转换会全表扫描"><a href="#7、强制类型转换会全表扫描" class="headerlink" title="7、强制类型转换会全表扫描"></a><strong>7、强制类型转换会全表扫描</strong></h2><p>字符串类型不加单引号会导致索引失效，因为mysql会自己做类型转换,相当于在索引列上进行了操作。</p>
<p>如果 phone 字段是 varchar 类型，则下面的 SQL 不能命中索引。</p>
<figure class="highlight n1ql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs n1ql"><span class="hljs-keyword">select</span> * <span class="hljs-keyword">from</span> <span class="hljs-keyword">user</span> <span class="hljs-keyword">where</span> phone=<span class="hljs-number">13800001234</span> <br></code></pre></td></tr></table></figure>

<p>可以优化为：</p>
<figure class="highlight n1ql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs n1ql"><span class="hljs-keyword">select</span> * <span class="hljs-keyword">from</span> <span class="hljs-keyword">user</span> <span class="hljs-keyword">where</span> phone=<span class="hljs-string">&#x27;13800001234&#x27;</span>; <br></code></pre></td></tr></table></figure>

<h2 id="8、更新十分频繁、数据区分度不高的列不宜建立索引"><a href="#8、更新十分频繁、数据区分度不高的列不宜建立索引" class="headerlink" title="8、更新十分频繁、数据区分度不高的列不宜建立索引"></a><strong>8、更新十分频繁、数据区分度不高的列不宜建立索引</strong></h2><ul>
<li>更新会变更 B+ 树，更新频繁的字段建立索引会大大降低数据库性能。</li>
<li>“性别”这种区分度不大的属性，建立索引是没有什么意义的，不能有效过滤数据，性能与全表扫描类似。</li>
<li>一般区分度在80%以上的时候就可以建立索引，区分度可以使用 count(distinct(列名))/count(*) 来计算。</li>
</ul>
<h2 id="9、利用覆盖索引来进行查询操作，避免回表，减少select-的使用"><a href="#9、利用覆盖索引来进行查询操作，避免回表，减少select-的使用" class="headerlink" title="9、利用覆盖索引来进行查询操作，避免回表，减少select * 的使用"></a><strong>9、利用覆盖索引来进行查询操作，避免回表，减少select * 的使用</strong></h2><ul>
<li>覆盖索引：查询的列和所建立的索引的列个数相同，字段相同。</li>
<li>被查询的列，数据能从索引中取得，而不用通过行定位符 row-locator 再到 row 上获取，即“被查询列要被所建的索引覆盖”，这能够加速查询速度。</li>
<li>例如登录业务需求，SQL语句如下。</li>
</ul>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs routeros">Select uid, login_time <span class="hljs-keyword">from</span><span class="hljs-built_in"> user </span>where <span class="hljs-attribute">login_name</span>=? <span class="hljs-keyword">and</span> <span class="hljs-attribute">passwd</span>=? <br></code></pre></td></tr></table></figure>

<ul>
<li>可以建立(login_name, passwd, login_time)的联合索引，由于 login_time 已经建立在索引中了，被查询的 uid 和 login_time 就不用去 row 上获取数据了，从而加速查询。</li>
</ul>
<h2 id="10、索引不会包含有NULL值的列"><a href="#10、索引不会包含有NULL值的列" class="headerlink" title="10、索引不会包含有NULL值的列"></a><strong>10、索引不会包含有NULL值的列</strong></h2><p>只要列中包含有NULL值都将不会被包含在索引中，复合索引中只要有一列含有NULL值，那么这一列对于此复合索引就是无效的。所以我们在数据库设计时，尽量使用not null 约束以及默认值。</p>
<h2 id="11、is-null-is-not-null无法使用索引"><a href="#11、is-null-is-not-null无法使用索引" class="headerlink" title="11、is null, is not null无法使用索引"></a><strong>11、is null, is not null无法使用索引</strong></h2><h2 id="12、如果有order-by、group-by的场景，请注意利用索引的有序性"><a href="#12、如果有order-by、group-by的场景，请注意利用索引的有序性" class="headerlink" title="12、如果有order by、group by的场景，请注意利用索引的有序性"></a>12、如果有order by、group by的场景，请注意利用索引的有序性</h2><p>order by 最后的字段是组合索引的一部分，并且放在索引组合顺序的最后，避免出现file_sort 的情况，影响查询性能。</p>
<ul>
<li>例如对于语句 where a=? and b=? order by c，可以建立联合索引(a,b,c)。</li>
</ul>
<p>如果索引中有范围查找，那么索引有序性无法利用，如 WHERE a&gt;10 ORDER BY b;，索引(a,b)无法排序。</p>
<h2 id="13、使用短索引-前缀索引"><a href="#13、使用短索引-前缀索引" class="headerlink" title="13、使用短索引(前缀索引)"></a><strong>13、使用短索引(前缀索引)</strong></h2><ul>
<li>对列进行索引，如果可能应该指定一个前缀长度。例如，如果有一个CHAR(255)的列，如果该列在前10个或20个字符内，可以做到既使得前缀索引的区分度接近全列索引，那么就不要对整个列进行索引。因为短索引不仅可以提高查询速度而且可以节省磁盘空间和I/O操作，减少索引文件的维护开销。可以使用count(distinct leftIndex(列名, 索引长度))/count(*) 来计算前缀索引的区分度。</li>
<li>但缺点是不能用于 ORDER BY 和 GROUP BY 操作，也不能用于覆盖索引。</li>
<li>不过很多时候没必要对全字段建立索引，根据实际文本区分度决定索引长度即可。</li>
</ul>
<h2 id="14、利用延迟关联或者子查询优化超多分页场景"><a href="#14、利用延迟关联或者子查询优化超多分页场景" class="headerlink" title="14、利用延迟关联或者子查询优化超多分页场景"></a><strong>14、利用延迟关联或者子查询优化超多分页场景</strong></h2><p>MySQL 并不是跳过 offset 行，而是取 offset+N 行，然后返回放弃前 offset 行，返回 N 行，那当 offset 特别大的时候，效率就非常的低下，要么控制返回的总页数，要么对超过特定阈值的页数进行 SQL 改写。</p>
<p>示例如下，先快速定位需要获取的id段，然后再关联:</p>
<figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs applescript">selecta.* <span class="hljs-keyword">from</span> 表<span class="hljs-number">1</span> a,(select <span class="hljs-built_in">id</span> <span class="hljs-keyword">from</span> 表<span class="hljs-number">1</span> <span class="hljs-keyword">where</span> 条件 limit100000,<span class="hljs-number">20</span> ) b <span class="hljs-keyword">where</span> a.<span class="hljs-built_in">id</span>=b.<span class="hljs-built_in">id</span>； <br></code></pre></td></tr></table></figure>

<h2 id="15、如果明确知道只有一条结果返回，limit-1-能够提高效率"><a href="#15、如果明确知道只有一条结果返回，limit-1-能够提高效率" class="headerlink" title="15、如果明确知道只有一条结果返回，limit 1 能够提高效率"></a><strong>15、如果明确知道只有一条结果返回，limit 1 能够提高效率</strong></h2><ul>
<li>比如如下 SQL 语句：</li>
</ul>
<figure class="highlight n1ql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs n1ql"><span class="hljs-keyword">select</span> * <span class="hljs-keyword">from</span> <span class="hljs-keyword">user</span> <span class="hljs-keyword">where</span> login_name=?; <br></code></pre></td></tr></table></figure>

<ul>
<li>可以优化为：</li>
</ul>
<figure class="highlight n1ql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs n1ql"><span class="hljs-keyword">select</span> * <span class="hljs-keyword">from</span> <span class="hljs-keyword">user</span> <span class="hljs-keyword">where</span> login_name=? <span class="hljs-keyword">limit</span> <span class="hljs-number">1</span> <br></code></pre></td></tr></table></figure>

<p>自己明确知道只有一条结果，但数据库并不知道，明确告诉它，让它主动停止游标移动。</p>
<h2 id="16、超过三个表最好不要-join"><a href="#16、超过三个表最好不要-join" class="headerlink" title="16、超过三个表最好不要 join"></a><strong>16、超过三个表最好不要 join</strong></h2><ul>
<li>需要 join 的字段，数据类型必须一致，多表关联查询时，保证被关联的字段需要有索引。</li>
<li>例如：left join是由左边决定的，左边的数据一定都有，所以右边是我们的关键点，建立索引要建右边的。当然如果索引在左边，可以用right join。</li>
</ul>
<h2 id="17、单表索引建议控制在5个以内"><a href="#17、单表索引建议控制在5个以内" class="headerlink" title="17、单表索引建议控制在5个以内"></a><strong>17、单表索引建议控制在5个以内</strong></h2><h2 id="18、SQL-性能优化-explain-中的-type：至少要达到-range-级别，要求是-ref-级别，如果可以是-consts-最好"><a href="#18、SQL-性能优化-explain-中的-type：至少要达到-range-级别，要求是-ref-级别，如果可以是-consts-最好" class="headerlink" title="18、SQL 性能优化 explain 中的 type：至少要达到 range 级别，要求是 ref 级别，如果可以是 consts 最好"></a><strong>18、SQL 性能优化 explain 中的 type：至少要达到 range 级别，要求是 ref 级别，如果可以是 consts 最好</strong></h2><ul>
<li>consts：单表中最多只有一个匹配行(主键或者唯一索引)，在优化阶段即可读取到数据。</li>
<li>ref：使用普通的索引(Normal Index)。</li>
<li>range：对索引进行范围检索。</li>
<li>当 type=index 时，索引物理文件全扫，速度非常慢。</li>
</ul>
<h2 id="19、业务上具有唯一特性的字段，即使是多个字段的组合，也必须建成唯一索引"><a href="#19、业务上具有唯一特性的字段，即使是多个字段的组合，也必须建成唯一索引" class="headerlink" title="19、业务上具有唯一特性的字段，即使是多个字段的组合，也必须建成唯一索引"></a><strong>19、业务上具有唯一特性的字段，即使是多个字段的组合，也必须建成唯一索引</strong></h2><p>不要以为唯一索引影响了 insert 速度，这个速度损耗可以忽略，但提高查找速度是明显的。另外，即使在应用层做了非常完善的校验控制，只要没有唯一索引，根据墨菲定律，必然有脏数据产生。</p>
<h2 id="20-创建索引时避免以下错误观念"><a href="#20-创建索引时避免以下错误观念" class="headerlink" title="20.创建索引时避免以下错误观念"></a><strong>20.创建索引时避免以下错误观念</strong></h2><p>索引越多越好，认为需要一个查询就建一个索引。</p>
<p>宁缺勿滥，认为索引会消耗空间、严重拖慢更新和新增速度。</p>
<p>抵制惟一索引，认为业务的惟一性一律需要在应用层通过“先查后插”方式解决。</p>
<p>过早优化，在不了解系统的情况下就开始优化。</p>
<p><strong>索引选择性与前缀索引</strong></p>
<ul>
<li>既然索引可以加快查询速度，那么是不是只要是查询语句需要，就建上索引?答案是否定的。因为索引虽然加快了查询速度，但索引也是有代价的：索引文件本身要消耗存储空间，同时索引会加重插入、删除和修改记录时的负担，另外，MySQL在运行时也要消耗资源维护索引，因此索引并不是越多越好。一般两种情况下不建议建索引。</li>
<li>第一种情况是表记录比较少，例如一两千条甚至只有几百条记录的表，没必要建索引，让查询做全表扫描就好了。至于多少条记录才算多，这个个人有个人的看法，我个人的经验是以2000作为分界线，记录数不超过 2000可以考虑不建索引，超过2000条可以酌情考虑索引。</li>
<li>另一种不建议建索引的情况是索引的选择性较低。所谓索引的选择性(Selectivity)，是指不重复的索引值(也叫基数，Cardinality)与表记录数(#T)的比值：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">Index Selectivity &#x3D; Cardinality &#x2F; #T <br></code></pre></td></tr></table></figure>

<ul>
<li>显然选择性的取值范围为(0, 1]``，选择性越高的索引价值越大，这是由B+Tree的性质决定的。例如，employees.titles表，如果title`字段经常被单独查询，是否需要建索引，我们看一下它的选择性：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT count(DISTINCT(title))&#x2F;count(*) AS Selectivity FROM employees.titles; <br>+-------------+ <br>| Selectivity | <br>+-------------+ <br>|      0.0000 | <br>+-------------+ <br></code></pre></td></tr></table></figure>

<ul>
<li>title的选择性不足0.0001(精确值为0.00001579)，所以实在没有什么必要为其单独建索引。</li>
<li>有一种与索引选择性有关的索引优化策略叫做前缀索引，就是用列的前缀代替整个列作为索引key，当前缀长度合适时，可以做到既使得前缀索引的选择性接近全列索引，同时因为索引key变短而减少了索引文件的大小和维护开销。下面以employees.employees表为例介绍前缀索引的选择和使用。</li>
<li>假设employees表只有一个索引，那么如果我们想按名字搜索一个人，就只能全表扫描了：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs mysql">EXPLAIN SELECT * FROM employees.employees WHERE first_name&#x3D;&#39;Eric&#39; AND last_name&#x3D;&#39;Anido&#39;; <br>+----+-------------+-----------+------+---------------+------+---------+------+--------+-------------+ <br>| id | select_type | table     | type | possible_keys | key  | key_len | ref  | rows   | Extra       | <br>+----+-------------+-----------+------+---------------+------+---------+------+--------+-------------+ <br>|  1 | SIMPLE      | employees | ALL  | NULL          | NULL | NULL    | NULL | 300024 | Using where <br>| +----+-------------+-----------+------+---------------+------+---------+------+--------+-------------+ <br></code></pre></td></tr></table></figure>

<ul>
<li>如果频繁按名字搜索员工，这样显然效率很低，因此我们可以考虑建索引。有两种选择，建或</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT count(DISTINCT(first_name))&#x2F;count(*) AS Selectivity FROM employees.employees; <br>+-------------+ <br>| Selectivity | <br>+-------------+ <br>|      0.0042 | <br>+-------------+ <br>SELECT count(DISTINCT(concat(first_name,last_name)))&#x2F;count(*) AS Selectivity FROM employees.employees; <br>+-------------+ <br>| Selectivity | <br>+-------------+ <br>|      0.9313 | <br>+-------------+ <br></code></pre></td></tr></table></figure>

<ul>
<li><first_name>显然选择性太低，`&lt;first_name, last_name&gt;选择性很好，但是first_name和last_name加起来长度为30，有没有兼顾长度和选择性的办法？可以考虑用first_name和last_name的前几个字符建立索引，例如&lt;first_name, left(last_name, 3)&gt;，看看其选择性：</li>
</ul>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs pgsql"><span class="hljs-keyword">SELECT</span> count(<span class="hljs-keyword">DISTINCT</span>(concat(first_name, left(last_name, <span class="hljs-number">3</span>))))/count(*) <span class="hljs-keyword">AS</span> Selectivity <span class="hljs-keyword">FROM</span> employees.employees; <br>+<span class="hljs-comment">-------------+ </span><br>| Selectivity | <br>+<span class="hljs-comment">-------------+ </span><br>|      <span class="hljs-number">0.7879</span> | <br>+<span class="hljs-comment">-------------+ </span><br></code></pre></td></tr></table></figure>

<ul>
<li>选择性还不错，但离0.9313还是有点距离，那么把last_name前缀加到4：</li>
<li>```<br>SELECT count(DISTINCT(concat(first_name, left(last_name, 4))))/count(*) AS Selectivity FROM employees.employees;<br>+————-+<br>| Selectivity |<br>+————-+<br>|      0.9007 |<br>+————-+ <figure class="highlight asciidoc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs asciidoc"><br><span class="hljs-bullet">- </span>这时选择性已经很理想了，而这个索引的长度只有18，比<br><br></code></pre></td></tr></table></figure>
ALTER TABLE employees.employees ADD INDEX <code>first_name_last_name4</code> (first_name, last_name(4)); <figure class="highlight asciidoc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs asciidoc"><br><span class="hljs-bullet">- </span>此时再执行一遍按名字查询，比较分析一下与建索引前的结果：<br><br></code></pre></td></tr></table></figure>
SHOW PROFILES; </li>
</ul>
<p>+———-+————+———————————————————————————+<br>| Query_ID | Duration   | Query                                                                           |<br>+———-+————+———————————————————————————+<br>|       87 | 0.11941700 |<br>SELECT * FROM employees.employees WHERE first_name=’Eric’ AND last_name=’Anido’<br>| |       90 | 0.00092400 |<br>SELECT * FROM employees.employees WHERE first_name=’Eric’ AND last_name=’Anido’ |<br>+———-+————+———————————————————————————+ </p>
<p>```</p>
<ul>
<li>性能的提升是显著的，查询速度提高了120多倍。</li>
<li>前缀索引兼顾索引大小和查询速度，但是其缺点是不能用于ORDER BY和GROUP BY操作，也不能用于Covering index(即当索引本身包含查询所需全部数据时，不再访问数据文件本身)。</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="mailto:undefined">Li YunBO</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="http://example.com/2021/04/27/MySql%E7%B4%A2%E5%BC%95%E4%BC%98%E5%8C%96/">http://example.com/2021/04/27/MySql%E7%B4%A2%E5%BC%95%E4%BC%98%E5%8C%96/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/MySql/">MySql</a></div><div class="post_share"><div class="social-share" data-image="/img/%E5%A4%B4%E5%83%8F2.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/04/27/MySql%E5%93%AA%E4%BA%9B%E5%88%97%E9%80%82%E5%90%88%E5%BB%BA%E7%AB%8B%E7%B4%A2%E5%BC%95/"><img class="prev-cover" src="/" onerror="onerror=null;src='/img/404.png'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">哪些列适合建立索引</div></div></a></div><div class="next-post pull-right"><a href="/2021/04/27/MySql%E7%B4%A2%E5%BC%95%E5%A4%B1%E6%95%88/"><img class="next-cover" src="/" onerror="onerror=null;src='/img/404.png'" alt="cover of next post"><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">MySQL中索引失效的常见场景与规避方法</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> Related Articles</span></div><div class="relatedPosts-list"><div><a href="/2021/04/19/MySQL/" title="MySQL"><img class="cover" src="/" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-19</div><div class="title">MySQL</div></div></a></div><div><a href="/2021/04/19/MySql_distributed/" title="mysql面试题"><img class="cover" src="/" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-19</div><div class="title">mysql面试题</div></div></a></div><div><a href="/2021/04/19/MySql_index/" title="mysql索引"><img class="cover" src="/" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-19</div><div class="title">mysql索引</div></div></a></div><div><a href="/2021/04/19/MySql_lock/" title="数据库锁"><img class="cover" src="/" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-19</div><div class="title">数据库锁</div></div></a></div><div><a href="/2021/04/19/MySql_optimization/" title="索引优化"><img class="cover" src="/" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-19</div><div class="title">索引优化</div></div></a></div><div><a href="/2021/04/19/MySql_skill/" title="MySql 小技巧"><img class="cover" src="/" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-19</div><div class="title">MySql 小技巧</div></div></a></div></div></div></div><div class="aside_content" id="aside_content"><div class="card-widget card-info"><div class="card-content"><div class="card-info-avatar is-center"><img class="avatar-img" src="/img/%E5%A4%B4%E5%83%8F2.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">Li YunBO</div><div class="author-info__description">给自己的警言：不要止步不前，不要因循守缺，不要纸上谈兵，不要不思进取，不要一直不要！</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">193</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">25</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">Categories</div><div class="length-num">18</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/Sobremesa_bolg"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/Sobremesa_bolg" target="_blank" title="Gitee"><i class="fab fa-github"></i></a></div></div></div><div class="card-widget card-announcement"><div class="card-content"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>Announcement</span></div><div class="announcement_content">这是我的博客</div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="card-content"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#MySQL%E7%B4%A2%E5%BC%95%E5%A6%82%E4%BD%95%E4%BC%98%E5%8C%96%EF%BC%9F"><span class="toc-number">1.</span> <span class="toc-text">MySQL索引如何优化？</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81like%E8%AF%AD%E5%8F%A5%E7%9A%84%E5%89%8D%E5%AF%BC%E6%A8%A1%E7%B3%8A%E6%9F%A5%E8%AF%A2%E4%B8%8D%E8%83%BD%E4%BD%BF%E7%94%A8%E7%B4%A2%E5%BC%95"><span class="toc-number">1.1.</span> <span class="toc-text">1、like语句的前导模糊查询不能使用索引</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81union%E3%80%81in%E3%80%81or-%E9%83%BD%E8%83%BD%E5%A4%9F%E5%91%BD%E4%B8%AD%E7%B4%A2%E5%BC%95%EF%BC%8C%E5%BB%BA%E8%AE%AE%E4%BD%BF%E7%94%A8-in"><span class="toc-number">1.2.</span> <span class="toc-text">2、union、in、or 都能够命中索引，建议使用 in</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E8%B4%9F%E5%90%91%E6%9D%A1%E4%BB%B6%E6%9F%A5%E8%AF%A2%E4%B8%8D%E8%83%BD%E4%BD%BF%E7%94%A8%E7%B4%A2%E5%BC%95"><span class="toc-number">1.3.</span> <span class="toc-text">3、负向条件查询不能使用索引</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%E3%80%81%E8%81%94%E5%90%88%E7%B4%A2%E5%BC%95%E6%9C%80%E5%B7%A6%E5%89%8D%E7%BC%80%E5%8E%9F%E5%88%99"><span class="toc-number">1.4.</span> <span class="toc-text">4、联合索引最左前缀原则</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5%E3%80%81%E4%B8%8D%E8%83%BD%E4%BD%BF%E7%94%A8%E7%B4%A2%E5%BC%95%E4%B8%AD%E8%8C%83%E5%9B%B4%E6%9D%A1%E4%BB%B6%E5%8F%B3%E8%BE%B9%E7%9A%84%E5%88%97-%E8%8C%83%E5%9B%B4%E5%88%97%E5%8F%AF%E4%BB%A5%E7%94%A8%E5%88%B0%E7%B4%A2%E5%BC%95-%EF%BC%8C%E8%8C%83%E5%9B%B4%E5%88%97%E4%B9%8B%E5%90%8E%E5%88%97%E7%9A%84%E7%B4%A2%E5%BC%95%E5%85%A8%E5%A4%B1%E6%95%88"><span class="toc-number">1.5.</span> <span class="toc-text">5、不能使用索引中范围条件右边的列(范围列可以用到索引)，范围列之后列的索引全失效</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6%E3%80%81%E4%B8%8D%E8%A6%81%E5%9C%A8%E7%B4%A2%E5%BC%95%E5%88%97%E4%B8%8A%E9%9D%A2%E5%81%9A%E4%BB%BB%E4%BD%95%E6%93%8D%E4%BD%9C-%E8%AE%A1%E7%AE%97%E3%80%81%E5%87%BD%E6%95%B0-%EF%BC%8C%E5%90%A6%E5%88%99%E4%BC%9A%E5%AF%BC%E8%87%B4%E7%B4%A2%E5%BC%95%E5%A4%B1%E6%95%88%E8%80%8C%E8%BD%AC%E5%90%91%E5%85%A8%E8%A1%A8%E6%89%AB%E6%8F%8F"><span class="toc-number">1.6.</span> <span class="toc-text">6、不要在索引列上面做任何操作(计算、函数)，否则会导致索引失效而转向全表扫描</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7%E3%80%81%E5%BC%BA%E5%88%B6%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2%E4%BC%9A%E5%85%A8%E8%A1%A8%E6%89%AB%E6%8F%8F"><span class="toc-number">1.7.</span> <span class="toc-text">7、强制类型转换会全表扫描</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8%E3%80%81%E6%9B%B4%E6%96%B0%E5%8D%81%E5%88%86%E9%A2%91%E7%B9%81%E3%80%81%E6%95%B0%E6%8D%AE%E5%8C%BA%E5%88%86%E5%BA%A6%E4%B8%8D%E9%AB%98%E7%9A%84%E5%88%97%E4%B8%8D%E5%AE%9C%E5%BB%BA%E7%AB%8B%E7%B4%A2%E5%BC%95"><span class="toc-number">1.8.</span> <span class="toc-text">8、更新十分频繁、数据区分度不高的列不宜建立索引</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9%E3%80%81%E5%88%A9%E7%94%A8%E8%A6%86%E7%9B%96%E7%B4%A2%E5%BC%95%E6%9D%A5%E8%BF%9B%E8%A1%8C%E6%9F%A5%E8%AF%A2%E6%93%8D%E4%BD%9C%EF%BC%8C%E9%81%BF%E5%85%8D%E5%9B%9E%E8%A1%A8%EF%BC%8C%E5%87%8F%E5%B0%91select-%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-number">1.9.</span> <span class="toc-text">9、利用覆盖索引来进行查询操作，避免回表，减少select * 的使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10%E3%80%81%E7%B4%A2%E5%BC%95%E4%B8%8D%E4%BC%9A%E5%8C%85%E5%90%AB%E6%9C%89NULL%E5%80%BC%E7%9A%84%E5%88%97"><span class="toc-number">1.10.</span> <span class="toc-text">10、索引不会包含有NULL值的列</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#11%E3%80%81is-null-is-not-null%E6%97%A0%E6%B3%95%E4%BD%BF%E7%94%A8%E7%B4%A2%E5%BC%95"><span class="toc-number">1.11.</span> <span class="toc-text">11、is null, is not null无法使用索引</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#12%E3%80%81%E5%A6%82%E6%9E%9C%E6%9C%89order-by%E3%80%81group-by%E7%9A%84%E5%9C%BA%E6%99%AF%EF%BC%8C%E8%AF%B7%E6%B3%A8%E6%84%8F%E5%88%A9%E7%94%A8%E7%B4%A2%E5%BC%95%E7%9A%84%E6%9C%89%E5%BA%8F%E6%80%A7"><span class="toc-number">1.12.</span> <span class="toc-text">12、如果有order by、group by的场景，请注意利用索引的有序性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#13%E3%80%81%E4%BD%BF%E7%94%A8%E7%9F%AD%E7%B4%A2%E5%BC%95-%E5%89%8D%E7%BC%80%E7%B4%A2%E5%BC%95"><span class="toc-number">1.13.</span> <span class="toc-text">13、使用短索引(前缀索引)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#14%E3%80%81%E5%88%A9%E7%94%A8%E5%BB%B6%E8%BF%9F%E5%85%B3%E8%81%94%E6%88%96%E8%80%85%E5%AD%90%E6%9F%A5%E8%AF%A2%E4%BC%98%E5%8C%96%E8%B6%85%E5%A4%9A%E5%88%86%E9%A1%B5%E5%9C%BA%E6%99%AF"><span class="toc-number">1.14.</span> <span class="toc-text">14、利用延迟关联或者子查询优化超多分页场景</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#15%E3%80%81%E5%A6%82%E6%9E%9C%E6%98%8E%E7%A1%AE%E7%9F%A5%E9%81%93%E5%8F%AA%E6%9C%89%E4%B8%80%E6%9D%A1%E7%BB%93%E6%9E%9C%E8%BF%94%E5%9B%9E%EF%BC%8Climit-1-%E8%83%BD%E5%A4%9F%E6%8F%90%E9%AB%98%E6%95%88%E7%8E%87"><span class="toc-number">1.15.</span> <span class="toc-text">15、如果明确知道只有一条结果返回，limit 1 能够提高效率</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#16%E3%80%81%E8%B6%85%E8%BF%87%E4%B8%89%E4%B8%AA%E8%A1%A8%E6%9C%80%E5%A5%BD%E4%B8%8D%E8%A6%81-join"><span class="toc-number">1.16.</span> <span class="toc-text">16、超过三个表最好不要 join</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#17%E3%80%81%E5%8D%95%E8%A1%A8%E7%B4%A2%E5%BC%95%E5%BB%BA%E8%AE%AE%E6%8E%A7%E5%88%B6%E5%9C%A85%E4%B8%AA%E4%BB%A5%E5%86%85"><span class="toc-number">1.17.</span> <span class="toc-text">17、单表索引建议控制在5个以内</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#18%E3%80%81SQL-%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96-explain-%E4%B8%AD%E7%9A%84-type%EF%BC%9A%E8%87%B3%E5%B0%91%E8%A6%81%E8%BE%BE%E5%88%B0-range-%E7%BA%A7%E5%88%AB%EF%BC%8C%E8%A6%81%E6%B1%82%E6%98%AF-ref-%E7%BA%A7%E5%88%AB%EF%BC%8C%E5%A6%82%E6%9E%9C%E5%8F%AF%E4%BB%A5%E6%98%AF-consts-%E6%9C%80%E5%A5%BD"><span class="toc-number">1.18.</span> <span class="toc-text">18、SQL 性能优化 explain 中的 type：至少要达到 range 级别，要求是 ref 级别，如果可以是 consts 最好</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#19%E3%80%81%E4%B8%9A%E5%8A%A1%E4%B8%8A%E5%85%B7%E6%9C%89%E5%94%AF%E4%B8%80%E7%89%B9%E6%80%A7%E7%9A%84%E5%AD%97%E6%AE%B5%EF%BC%8C%E5%8D%B3%E4%BD%BF%E6%98%AF%E5%A4%9A%E4%B8%AA%E5%AD%97%E6%AE%B5%E7%9A%84%E7%BB%84%E5%90%88%EF%BC%8C%E4%B9%9F%E5%BF%85%E9%A1%BB%E5%BB%BA%E6%88%90%E5%94%AF%E4%B8%80%E7%B4%A2%E5%BC%95"><span class="toc-number">1.19.</span> <span class="toc-text">19、业务上具有唯一特性的字段，即使是多个字段的组合，也必须建成唯一索引</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#20-%E5%88%9B%E5%BB%BA%E7%B4%A2%E5%BC%95%E6%97%B6%E9%81%BF%E5%85%8D%E4%BB%A5%E4%B8%8B%E9%94%99%E8%AF%AF%E8%A7%82%E5%BF%B5"><span class="toc-number">1.20.</span> <span class="toc-text">20.创建索引时避免以下错误观念</span></a></li></ol></li></ol></div></div></div><div class="card-widget card-recent-post"><div class="card-content"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/08/16/%E6%B5%8B%E8%AF%95%E8%AE%B0%E5%BD%95/" title="测试"><img src="/img/%E5%92%8C%E6%9C%8D%E5%B0%91%E5%A5%B3.jpg%20img/%E8%9C%98%E8%9B%9B%E4%BE%A0.jpg" onerror="this.onerror=null;this.src='/img/404.png'" alt="测试"/></a><div class="content"><a class="title" href="/2021/08/16/%E6%B5%8B%E8%AF%95%E8%AE%B0%E5%BD%95/" title="测试">测试</a><time datetime="2021-08-16T01:20:46.666Z" title="Created 2021-08-16 09:20:46">2021-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/16/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E9%81%8D%E5%8E%86/" title="二叉树的遍历"><img src="/img/%E5%92%8C%E6%9C%8D%E5%B0%91%E5%A5%B3.jpg%20img/%E8%9C%98%E8%9B%9B%E4%BE%A0.jpg" onerror="this.onerror=null;this.src='/img/404.png'" alt="二叉树的遍历"/></a><div class="content"><a class="title" href="/2021/08/16/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E9%81%8D%E5%8E%86/" title="二叉树的遍历">二叉树的遍历</a><time datetime="2021-08-15T16:00:00.000Z" title="Created 2021-08-16 00:00:00">2021-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/10/%E8%AE%A4%E7%9C%9F%E7%9A%84+Netty+%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90%EF%BC%88%E4%BA%8C%EF%BC%89/" title="认真的 Netty 源码解析（二）"><img src="/img/%E5%92%8C%E6%9C%8D%E5%B0%91%E5%A5%B3.jpg%20img/%E8%9C%98%E8%9B%9B%E4%BE%A0.jpg" onerror="this.onerror=null;this.src='/img/404.png'" alt="认真的 Netty 源码解析（二）"/></a><div class="content"><a class="title" href="/2021/08/10/%E8%AE%A4%E7%9C%9F%E7%9A%84+Netty+%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90%EF%BC%88%E4%BA%8C%EF%BC%89/" title="认真的 Netty 源码解析（二）">认真的 Netty 源码解析（二）</a><time datetime="2021-08-10T07:53:27.000Z" title="Created 2021-08-10 15:53:27">2021-08-10</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/10/%E8%AE%A4%E7%9C%9F%E7%9A%84+Netty+%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90%EF%BC%88%E4%B8%80%EF%BC%89/" title="认真的 Netty 源码解析（一）"><img src="/img/%E5%92%8C%E6%9C%8D%E5%B0%91%E5%A5%B3.jpg%20img/%E8%9C%98%E8%9B%9B%E4%BE%A0.jpg" onerror="this.onerror=null;this.src='/img/404.png'" alt="认真的 Netty 源码解析（一）"/></a><div class="content"><a class="title" href="/2021/08/10/%E8%AE%A4%E7%9C%9F%E7%9A%84+Netty+%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90%EF%BC%88%E4%B8%80%EF%BC%89/" title="认真的 Netty 源码解析（一）">认真的 Netty 源码解析（一）</a><time datetime="2021-08-10T07:53:15.000Z" title="Created 2021-08-10 15:53:15">2021-08-10</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/10/Java+%E9%9D%9E%E9%98%BB%E5%A1%9E+IO+%E5%92%8C%E5%BC%82%E6%AD%A5+IO/" title="Java 非阻塞 IO 和异步 IO"><img src="/img/%E5%92%8C%E6%9C%8D%E5%B0%91%E5%A5%B3.jpg%20img/%E8%9C%98%E8%9B%9B%E4%BE%A0.jpg" onerror="this.onerror=null;this.src='/img/404.png'" alt="Java 非阻塞 IO 和异步 IO"/></a><div class="content"><a class="title" href="/2021/08/10/Java+%E9%9D%9E%E9%98%BB%E5%A1%9E+IO+%E5%92%8C%E5%BC%82%E6%AD%A5+IO/" title="Java 非阻塞 IO 和异步 IO">Java 非阻塞 IO 和异步 IO</a><time datetime="2021-08-10T07:52:59.000Z" title="Created 2021-08-10 15:52:59">2021-08-10</time></div></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By Li YunBO</div><div class="framework-info"><span>Framework </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>Theme </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginModelPath":"assets/","model":{"jsonPath":"live2d-widget-model-koharu"},"display":{"position":"left","width":150,"height":300},"mobile":{"show":false},"rect":"opacity:0.7","log":false,"pluginJsPath":"lib/","pluginRootPath":"live2dw/","tagMode":false});</script></body></html>